package com.atsmart.app.activity;

import java.io.IOException;
import java.io.Serializable;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.adapter.LoadingAdapter;
import com.atsmart.app.adapter.ProductDetailAdapter;
import com.atsmart.app.exception.BizException;
import com.atsmart.app.model.ProductInfo;
import com.atsmart.app.model.ProductListInfo;
import com.atsmart.app.model.ResultInfo;
import com.atsmart.app.sql.ProductSqlHelper;
import com.atsmart.app.utils.IntentUtil;
import com.atsmart.app.utils.PersistentKeyUtil;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceAsynTask;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.google.json.Gson;
import com.google.json.JsonParseException;
import com.google.json.annotations.SerializedName;

public class ProductDetailListActivity extends BaseActivity implements
		LoadingAdapter.Delegate, LoadingAdapter.OnLoadingRowShowingHandler,
		OnClickListener, ProductDetailAdapter.ClickDelegate {
	private static final String TAG = ProductDetailListActivity.class.getName();
	private ListView listView;
	private ProductListInfo datasource;
	private ProductDetailAdapter adapter;
	private static final int pageSize = 1000;
	private boolean isNeedLoading = false;
	private int totalRow;
	private int pageIndex = 0;
	private String keyword;
	// private Button btnMap;
	// private Button btnRef;
	private ProductSqlHelper psql = null;
	private boolean asyntaskIsFinished = true;
	private int gid;
	private TextView search;
	private int product_id;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.product_detail_layout);
		init();
		psql = new ProductSqlHelper();
		psql.open(BizApp.getInstance().getSqlHelper());
		totalRow = psql.getCount();
	}

	private void init() {

		listView = (ListView) findViewById(R.id.listview);
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			keyword = bundle.getString(PersistentKeyUtil.PRODUCT_NAME);
			gid = bundle.getInt(PersistentKeyUtil.CLIENT_ID_STRING, 0);
			product_id = bundle.getInt("product_id");
			Log.e("TAG", "product_id: = " + product_id);
			if (keyword != null) {
				TextView title = (TextView) findViewById(R.id.title);
				title.setText("搜索结果");
				search = (TextView) findViewById(R.id.searchRe);
			}
		}
	}

	@Override
	protected void onResume() {
		super.onResume();

		if (asyntaskIsFinished) {
			pageIndex = 0;
			showLoading();
			getData();
		}
	}

	public class Phone implements Serializable {

		/**
		 *
		 */
		private static final long serialVersionUID = -6760611499805749529L;
		@SerializedName("phone")
		public String phone;
	}

	 
	private void getData() {
		registerLoadStatus(TAG);
		new ServiceAsynTask<ProductListInfo>() {

			@Override
			protected ProductListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException {
				int begin = pageIndex * pageSize;
				return psql.getProductInfo(begin, pageSize, keyword, gid);
			}

			@Override
			protected void runWithResult(ProductListInfo result)
					throws Exception {
				if (result == null || result.getProducts() == null
						|| result.getProducts().size() <= 0) {
					listView.setVisibility(View.INVISIBLE);
					search.setText("抱歉，没有找到与" + keyword + "相关的内容！");
				}else{
					listView.setVisibility(View.VISIBLE);
				}
				if (result != null) {
					datasource = result;

					bindData();
				}
				asyntaskIsFinished = true;
				finishedLoad(TAG);
			}

			@Override
			protected void runWithError(ProductListInfo result, int iErrorCode)
					throws Exception {
				asyntaskIsFinished = true;
				loadingFailed(TAG, iErrorCode);
			}
		}.execute();
	}

	private void bindData() {
		if (adapter == null || pageIndex == 0) {
			adapter = new ProductDetailAdapter(datasource, this);
			adapter.setDelegate(this);
			adapter.setHandler(this);
			adapter.setClickDelegate(this);
			listView.setAdapter(adapter);
		} else {
			if (pageIndex >= 1) {
				adapter.appendDataSource(datasource);
				adapter.notifyDataSetChanged();
			}
		}
		totalRow = datasource.getRows();
		if (totalRow > (pageIndex + 1) * pageSize) {
			isNeedLoading = true;
		} else {
			isNeedLoading = false;
		}
	}

	@Override
	public void onLoadingRowShowing(LoadingAdapter adapter) {
		if (pageIndex * pageSize < totalRow) {
			if (asyntaskIsFinished) {
				pageIndex++;
				getData();
				asyntaskIsFinished = false;
			}
		}
	}

	@Override
	public boolean needLoading() {
		return isNeedLoading;
	}

	private void showMap() {
		if (datasource == null) {
			return;
		}
		Bundle bundle = new Bundle();
		bundle.putSerializable(PersistentKeyUtil.CLIENTS_STRING, datasource);
		IntentUtil.redirectToNext(ProductDetailListActivity.this,
				ClientsMapActivity.class, bundle);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_refresh:
			showLoading();
			pageIndex = 0;
			getData();
			break;
		case R.id.btn_history:
			showMap();
			break;
		case R.id.btn_search:
			if (StringUtil.isEmptyOrNull(keyword)) {
				Toast.makeText(this, "请输入查询关键字", Toast.LENGTH_SHORT).show();
			} else {
				showLoading();
				getData();
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onItemClick(int position) {
		if (adapter == null) {
			return;
		}
		ProductInfo clientInfo = (ProductInfo) adapter.getItem(position);
		Bundle bundle = new Bundle();
		bundle.putString(PersistentKeyUtil.PRODUCT_NAME, clientInfo.getName());
		bundle.putInt(PersistentKeyUtil.CLIENT_ID_STRING,
				clientInfo.getProduct_id());
		IntentUtil.redirectToNext(ProductDetailListActivity.this,
				ProductItemActivity.class, bundle);
	}

}
